package org.qianji.goosql.cond;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.qianji.goosql.field.Field;
import org.qianji.goosql.operator.Comparator;

/**
 * BETWEEN查询条件。
 * 
 * @author gmz
 * 
 */
public class Between extends AbstractCondition {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8680730852988930978L;

	private Field field;
	private Object leftValue, rightValue;

	/**
	 * 有字段、最小值、最大值构造BETWEEN查询条件。
	 * 
	 * @param field
	 *            {@link Field} 字段
	 * @param leftValue
	 *            {@link Object} 最小值
	 * @param rightValue
	 *            {@link Object} 最大值
	 */
	public Between(Field field, Object leftValue, Object rightValue) {
		super();
		if (field == null || leftValue == null || rightValue == null) {
			throw new NullPointerException("args can't be null");
		}
		this.field = field;
		this.leftValue = leftValue;
		this.rightValue = rightValue;
	}

	/**
	 * 获取字段。
	 * 
	 * @return {@link Field} 字段
	 */
	public Field getField() {
		return field;
	}

	/**
	 * 获取最小值。
	 * 
	 * @return {@link Object} 最小值
	 */
	public Object getLeftValue() {
		return leftValue;
	}

	/**
	 * 获取最大值。
	 * 
	 * @return {@link Object} 最大值
	 */
	public Object getRightValue() {
		return rightValue;
	}

	@Override
	public String toSql() {
		StringBuffer cond = new StringBuffer();
		cond.append(field.toSql()).append(" ").append(Comparator.BTW).append(" ? and ?");
		return cond.toString();
	}

	@Override
	public List<Object> getPlacedParameters() {
		List<Object> ppl = new ArrayList<Object>();
		ppl.addAll(field.getPlacedParameters());
		ppl.add(leftValue);
		ppl.add(rightValue);
		return ppl;
	}

	@Override
	public Map<String, Object> getNamedParameters() {
		return field.getNamedParameters();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null || !(obj instanceof Between)) {
			return false;
		}
		Between other = (Between) obj;
		if (field.equals(other.getField()) && leftValue.equals(other.getLeftValue())
				&& rightValue.equals(other.getRightValue())) {
			return true;
		}
		return false;
	}

	@Override
	public int hashCode() {
		int hc = 37 * 17 + field.hashCode();
		hc = 37 * hc + leftValue.hashCode();
		hc = 37 * hc + rightValue.hashCode();
		return hc;
	}

	@Override
	public String toString() {
		return toSql();
	}

}
